import 'dart:math';

import 'package:flutter_menu/app_config.dart';
import 'package:flutter_menu/biz/order/order_controller.dart';
import 'package:flutter_menu/biz/search/search_pg.dart';
import 'package:flutter_menu/gen/assets.gen.dart';
import 'package:flutter_menu/menu_page.dart';
import 'package:flutter_menu/model/menu_model.dart';
import 'package:flutter_menu/res/app_design.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

final mainTabHeight = 0.08.sh;

class BottomTab extends GetView<OrderController> {
  BottomTab({super.key});

  OverlayEntry? _overlayEntryForCategory;
  static double categoryItemWidth = (ScreenUtil().screenWidth - 52.w) / 2;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<OrderController>(
        dispose: (_) => removeHighlightOverlay(),
        builder: (controller) {
          return Container(
              height: mainTabHeight,
              color: AppColors.bgTab,
              child: Row(
                children: [
                  InkWell(
                    onTap: () {
                      if(AppConfig.instance.loginModel == null){
                        Get.offAndToNamed(MenuPages.Menu_Login);
                      }else{
                        Get.offAndToNamed(MenuPages.Menu_Setting);
                      }
                    },
                    child: SizedBox(
                      height: mainTabHeight,
                      width: mainTabHeight,
                      child: MyAssets.images.icSetting
                          .image(width: 29.w, height: 32.w)
                          .center(),
                    ),
                  ),
                  Expanded(
                    child: Obx(() {
                      return Row(
                        children: [
                          BottomTabItem(
                            index: OrderTabType.tabSearch,
                            title: "orderTabItemSearch",
                            selectedIndex: controller.currentTabIndex.value,
                            onClickCallback: () {
                              removeHighlightOverlay();
                              controller.setTabIndex(OrderTabType.tabSearch);
                            },
                          ).expanded(),
                          BottomTabItem(
                            index: OrderTabType.tabCategory,
                            title: "orderTabItemCategory",
                            selectedIndex: controller.currentTabIndex.value,
                            onClickCallback: () {
                              _showCategoryOverlay(context, controller);
                            },
                          ).expanded(),
                          BottomTabItem(
                            index: OrderTabType.tabThumbnail,
                            title: "orderTabItemThumbnail",
                            selectedIndex: controller.isShowDetail
                                ? null
                                : controller.currentTabIndex.value,
                            onClickCallback: () {
                              removeHighlightOverlay();
                              controller.dismissDetailShow();
                              controller.setTabDefault();
                            },
                          ).expanded()
                        ],
                      );
                    }),
                  ),
                  // 固定宽度组件
                  GestureDetector(
                    onTap: () {
                      Get.offAllNamed(MenuPages.Menu_Order_Record);
                    },
                    child: Container(
                      width: 212.w, // 固定宽度
                      decoration: BoxDecoration(
                          color: AppColors.bgCard,
                          borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(mainTabHeight / 2),
                              bottomLeft: Radius.circular(mainTabHeight / 2))),
                      child: Center(
                          child: Text(
                        "orderTabItemOrdered".tr,
                        style: TextStyle(color: Colors.white, fontSize: 25.sp),
                      )),
                    ),
                  ),
                ],
              ));
        });
  }

  void _showCategoryOverlay(BuildContext context, OrderController controller) {
    if (_overlayEntryForCategory != null) {
      // removeHighlightOverlay();
      // controller.setTabDefault();
      return;
    }

    if (controller.categoryList.isEmpty) {
      return;
    }

    controller.setTabIndex(OrderTabType.tabCategory);

    _overlayEntryForCategory = OverlayEntry(
      builder: (context) => Stack(
        children: [
          GestureDetector(
            onTap: () {
              removeHighlightOverlay(); // 点击空白处关闭
              controller.resetCategoryTab();
            },
            child: Container(
              color: Colors.black.withOpacity(0.1), // 背景遮罩
            ),
          ),
          Positioned(
            bottom: mainTabHeight,
            // Adjust this to position the BottomSheet
            left: 0,
            right: 0,
            child: Container(
              decoration: BoxDecoration(
                color: AppColors.bgBottomSheet,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(16.w),
                    topRight: Radius.circular(16.w)),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1), // 阴影颜色
                    spreadRadius: 0, // 扩散半径
                    blurRadius: 13, // 模糊半径
                    offset: const Offset(0, 0), // 阴影偏移
                  ),
                ],
              ),
              padding: EdgeInsets.only(
                  left: 16.w, top: 35.w, right: 16.w, bottom: 19.w),
              child: Wrap(
                spacing: 20.0.w, // 水平方向的间距
                runSpacing: 24.0.w, // 垂直方向的间距
                children: controller.categoryList.map((item) {
                  return Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10.w),
                        boxShadow: [
                          BoxShadow(
                              color: Colors.black.withOpacity(0.35),
                              spreadRadius: 0,
                              blurRadius: 13,
                              offset: const Offset(0, 0))
                        ]),
                    child: ElevatedButton(
                      onPressed: () {
                        // 按钮点击事件
                        onCategorySelected(item);
                      },
                      style: ElevatedButton.styleFrom(
                          shadowColor: Colors.black.withOpacity(0.35),
                          elevation: 0,
                          backgroundColor: AppColors.buttonBgInBottomSheet,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10.w))),
                      child: Text('${item.categoryName}',
                          style: TextStyle(
                              height: 1.2,
                              color: AppColors.textInBottomSheet,
                              fontSize: 28.sp)),
                    ).size(width: BottomTab.categoryItemWidth, height: 70.w),
                  );
                }).toList(),
              ),
            ),
          ),
        ],
      ),
    );

    Overlay.of(context).insert(_overlayEntryForCategory!);
  }

  void onCategorySelected(CustomMenuListCategoryList item) {
    debugPrint('onCategorySelected: ${item.uuid}');
    var name = item.categoryName;
    if (name != null) {
      controller.currentCategoryName = name;
    }
    removeHighlightOverlay();
    controller.dismissDetailShow();
    controller.setTabDefault();
  }

  // Remove the OverlayEntry.
  void removeHighlightOverlay() {
    _overlayEntryForCategory?.remove();
    _overlayEntryForCategory?.dispose();
    _overlayEntryForCategory = null;
  }
}

class BottomTabItem extends StatelessWidget {
  const BottomTabItem(
      {super.key,
      required this.title,
      required this.index,
      this.selectedIndex,
      required this.onClickCallback});

  final String title;
  final OrderTabType index;
  final OrderTabType? selectedIndex;
  final VoidCallback onClickCallback;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onClickCallback,
      child: Stack(
        children: [
          Center(
              child: Text(
            title.tr,
            style: TextStyle(color: Colors.white, fontSize: 25.sp),
          )),
          Visibility(
            visible: index == selectedIndex,
            child: Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: MyAssets.images.icTri.image(width: 19.w, height: 13.w)),
          )
        ],
      ),
    );
  }
}
